/*
 * Copyright (C), 2002-2015, 你的兔宝宝电子商务有限公司
 * FileName: TemplateEditor.java
 * Author:   你的兔宝宝
 * Date:     2015-10-22 下午5:59:20
 * Description: freemarker模板属性编辑器//模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.baby.demo.utils.editor;

import java.io.StringReader;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceEditor;

import com.baby.demo.utils.Strings;

import freemarker.template.Template;

/**
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author 你的兔宝宝
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class TemplateEditor extends ResourceEditor {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(TemplateEditor.class);
    
    String classPathPrefix = "classpath";
    private static final String ENCODING = "UTF-8";
    String encoding;
    
    @Override
    public void setAsText(String text) {
        Template tpl = resolve(text);
        setValue(tpl);
    }
    
    public Template resolve(String text){
        Template tpl = null;
        String tplText = text;
        String path = Strings.show(text);
        if( path.startsWith(classPathPrefix) ){
            super.setAsText(text);
            Resource resource = (Resource) super.getValue();
            try {
                tplText = IOUtils.toString(resource.getInputStream(),Strings.show(encoding,ENCODING));
            } catch (Exception e) {
                LOGGER.error("读取模板异常",e);
            }
        }
        tpl = makeTpl(tplText);
        return tpl;
    }
    
    public Template makeTpl(String text){
        Template tpl = null;
        try {
            tpl = new Template("template-editor",new StringReader(text), null );
        } catch (Exception e) {
            LOGGER.error("模板编辑器异常",e);
            throw new IllegalArgumentException("模板属性编辑器异常",e);
        }
        return tpl;
    }
    
    @Override
    public String getAsText() {
        Template tpl =  (Template) getValue();
        return Strings.show(tpl);
    }

    /**
     * @return the classPathPrefix
     */
    public String getClassPathPrefix() {
        return classPathPrefix;
    }

    /**
     * @param classPathPrefix the classPathPrefix to set
     */
    public void setClassPathPrefix(String classPathPrefix) {
        this.classPathPrefix = classPathPrefix;
    }

    /**
     * @return the encoding
     */
    public String getEncoding() {
        return encoding;
    }

    /**
     * @param encoding the encoding to set
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }
    
}
